package com.deliveryservicesystem.service.crud.impl;

import com.deliveryservicesystem.app.exceptions.NonexistentEntityException;
import com.deliveryservicesystem.app.exceptions.PreexistingEntityException;
import com.deliveryservicesystem.dataaccess.PersistenceDbManager;
import com.deliveryservicesystem.model.Product;
import com.deliveryservicesystem.model.Supplier;
import com.deliveryservicesystem.service.crud.SupplierCrudService;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityNotFoundException;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

/**
 * File Name: SupplierCrudServiceImpl.java
 * Version:
 * Description:
 * Package: com.deliveryservicesystem.service.crud.impl
 * Author: Lance
 * Date: Jun 20, 2012
 * Editor:
 */
public class SupplierCrudServiceImpl implements SupplierCrudService
{

    private static final long serialVersionUID = 1L;
    private EntityManagerFactory emf = null;

    /**
     * Create the new CRUD service. Internally setting the EntityManagerFactory
     * using database details from database properties
     */
    public SupplierCrudServiceImpl()
    {
        PersistenceDbManager persistenceManager = PersistenceDbManager.getInstance();
        this.emf = persistenceManager.getEntityManagerFactory();
    }

    @Override
    public EntityManager getEntityManager()
    {
        return emf.createEntityManager();
    }

    @Override
    public void create(Supplier supplier) throws PreexistingEntityException, Exception
    {
        if (supplier.getProductList() == null)
        {
            supplier.setProductList(new ArrayList<Product>());
        }
        EntityManager em = null;
        try
        {
            em = getEntityManager();
            em.getTransaction().begin();
            List<Product> attachedProductList = new ArrayList<>();
            for (Product productListProductToAttach : supplier.getProductList())
            {
                productListProductToAttach = em.getReference(productListProductToAttach.getClass(), productListProductToAttach.getProductNo());
                attachedProductList.add(productListProductToAttach);
            }
            supplier.setProductList(attachedProductList);
            em.persist(supplier);
            for (Product productListProduct : supplier.getProductList())
            {
                Supplier oldSupplierNoOfProductListProduct = productListProduct.getSupplierNo();
                productListProduct.setSupplierNo(supplier);
                productListProduct = em.merge(productListProduct);
                if (oldSupplierNoOfProductListProduct != null)
                {
                    oldSupplierNoOfProductListProduct.getProductList().remove(productListProduct);
                    oldSupplierNoOfProductListProduct = em.merge(oldSupplierNoOfProductListProduct);
                }
            }
            em.getTransaction().commit();
        }
        catch (Exception ex)
        {
            if (findById(supplier.getSupplierNo()) != null)
            {
                throw new PreexistingEntityException("Supplier " + supplier + " already exists.", ex);
            }
            throw ex;
        }
        finally
        {
            if (em != null)
            {
                em.close();
            }
        }
    }

    @Override
    public void edit(Supplier supplier) throws NonexistentEntityException, Exception
    {
        EntityManager em = null;
        try
        {
            em = getEntityManager();
            em.getTransaction().begin();
            Supplier persistentSupplier = em.find(Supplier.class, supplier.getSupplierNo());
            List<Product> productListOld = persistentSupplier.getProductList();
            List<Product> productListNew = supplier.getProductList();
            List<Product> attachedProductListNew = new ArrayList<>();
            for (Product productListNewProductToAttach : productListNew)
            {
                productListNewProductToAttach = em.getReference(productListNewProductToAttach.getClass(), productListNewProductToAttach.getProductNo());
                attachedProductListNew.add(productListNewProductToAttach);
            }
            productListNew = attachedProductListNew;
            supplier.setProductList(productListNew);
            supplier = em.merge(supplier);
            for (Product productListOldProduct : productListOld)
            {
                if (!productListNew.contains(productListOldProduct))
                {
                    productListOldProduct.setSupplierNo(null);
                    productListOldProduct = em.merge(productListOldProduct);
                }
            }
            for (Product productListNewProduct : productListNew)
            {
                if (!productListOld.contains(productListNewProduct))
                {
                    Supplier oldSupplierNoOfProductListNewProduct = productListNewProduct.getSupplierNo();
                    productListNewProduct.setSupplierNo(supplier);
                    productListNewProduct = em.merge(productListNewProduct);
                    if (oldSupplierNoOfProductListNewProduct != null && !oldSupplierNoOfProductListNewProduct.equals(supplier))
                    {
                        oldSupplierNoOfProductListNewProduct.getProductList().remove(productListNewProduct);
                        oldSupplierNoOfProductListNewProduct = em.merge(oldSupplierNoOfProductListNewProduct);
                    }
                }
            }
            em.getTransaction().commit();
        }
        catch (Exception ex)
        {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0)
            {
                Integer id = supplier.getSupplierNo();
                if (findById(id) == null)
                {
                    throw new NonexistentEntityException("The supplier with id " + id + " no longer exists.");
                }
            }
            throw ex;
        }
        finally
        {
            if (em != null)
            {
                em.close();
            }
        }
    }

    @Override
    public void destroy(Integer id) throws NonexistentEntityException
    {
        EntityManager em = null;
        try
        {
            em = getEntityManager();
            em.getTransaction().begin();
            Supplier supplier;
            try
            {
                supplier = em.getReference(Supplier.class, id);
                supplier.getSupplierNo();
            }
            catch (EntityNotFoundException enfe)
            {
                throw new NonexistentEntityException("The supplier with id " + id + " no longer exists.", enfe);
            }
            List<Product> productList = supplier.getProductList();
            for (Product productListProduct : productList)
            {
                productListProduct.setSupplierNo(null);
                productListProduct = em.merge(productListProduct);
            }
            em.remove(supplier);
            em.getTransaction().commit();
        }
        finally
        {
            if (em != null)
            {
                em.close();
            }
        }
    }

    @Override
    public List<Supplier> findEntities()
    {
        return findSupplierEntities(true, -1, -1);
    }

    @Override
    public List<Supplier> findEntities(int maxResults, int firstResult)
    {
        return findSupplierEntities(false, maxResults, firstResult);
    }

    private List<Supplier> findSupplierEntities(boolean all, int maxResults, int firstResult)
    {
        EntityManager em = getEntityManager();
        try
        {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Supplier.class));
            Query q = em.createQuery(cq);
            if (!all)
            {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        }
        finally
        {
            em.close();
        }
    }

    @Override
    public Supplier findById(Integer id)
    {
        EntityManager em = getEntityManager();
        try
        {
            return em.find(Supplier.class, id);
        }
        finally
        {
            em.close();
        }
    }

    @Override
    public int count()
    {
        EntityManager em = getEntityManager();
        try
        {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Supplier> rt = cq.from(Supplier.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        }
        finally
        {
            em.close();
        }
    }
}
